package com.gh.shopmall.product.exception;

import com.gh.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Eric Fang
 * @version 1.0
 * @date 2021/11/21 16:21
 */
@ResponseBody
@Slf4j
@ControllerAdvice(basePackages = "com.gh.shopmall.product.controller")
public class ShopmallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handle(MethodArgumentNotValidException e) {
        Map<String, String> map = new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();
        //获取校验的错误结果
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        fieldErrors.forEach(fieldError -> {
            String message = fieldError.getDefaultMessage();//错误提示消息
            String field = fieldError.getField(); //获取错误的属性名
            map.put(field, message);
        });
        log.info("数据校验出现问题{},异常类型{}", e.getMessage(), e.getClass());
        return R.error().put("map", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        throwable.printStackTrace();
        return R.error();
    }
}
